package com.ruoyi.project.bill.aftersales.controller;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.bill.aftersalesItems.domain.BillAftersalesItems;
import com.ruoyi.project.bill.aftersalesItems.service.IBillAftersalesItemsService;
import com.ruoyi.project.bill.aftersalesOperateHistory.domain.BillAftersalesOperateHistory;
import com.ruoyi.project.bill.aftersalesOperateHistory.mapper.BillAftersalesOperateHistoryMapper;
import com.ruoyi.project.bill.exchange.domain.BillExchange;
import com.ruoyi.project.bill.exchange.service.IBillExchangeService;
import com.ruoyi.project.bill.refund.domain.BillRefund;
import com.ruoyi.project.bill.refund.service.IBillRefundService;
import com.ruoyi.project.bill.reship.domain.BillReship;
import com.ruoyi.project.bill.reship.service.IBillReshipService;
import com.ruoyi.project.mall.order.domain.OmsOrder;
import com.ruoyi.project.mall.order.service.IOmsOrderService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.bill.aftersales.domain.BillAftersales;
import com.ruoyi.project.bill.aftersales.service.IBillAftersalesService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 退货单Controller
 *
 * @author mallplus
 * @date 2020-03-12
 */
@Controller
@RequestMapping("/bill/aftersales")
public class BillAftersalesController extends BaseController {
    private String prefix = "bill/aftersales";

    @Autowired
    private IBillAftersalesService billAftersalesService;

    @RequiresPermissions("bill:aftersales:view")
    @GetMapping()
    public String aftersales() {
        return prefix + "/aftersales";
    }

    /**
     * 查询退货单列表
     */
    @RequiresPermissions("bill:aftersales:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BillAftersales billAftersales) {
        startPage();
        List<BillAftersales> list = billAftersalesService.selectBillAftersalesList(billAftersales);
        return getDataTable(list);
    }

    /**
     * 导出退货单列表
     */
    @RequiresPermissions("bill:aftersales:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BillAftersales billAftersales) {
        List<BillAftersales> list = billAftersalesService.selectBillAftersalesList(billAftersales);
        ExcelUtil<BillAftersales> util = new ExcelUtil<BillAftersales>(BillAftersales.class);
        return util.exportExcel(list, "aftersales");
    }

    /**
     * 新增退货单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存退货单
     */
    @RequiresPermissions("bill:aftersales:add")
    @Log(title = "退货单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(BillAftersales billAftersales) {
        return toAjax(billAftersalesService.insertBillAftersales(billAftersales));
    }

    /**
     * 修改退货单
     */
    @GetMapping("/edit/{aftersalesId}")
    public String edit(@PathVariable("aftersalesId") Long aftersalesId, ModelMap mmap) {
        BillAftersales billAftersales = billAftersalesService.selectBillAftersalesById(aftersalesId);
        mmap.put("billAftersales", billAftersales);
        return prefix + "/edit";
    }

    /**
     * 修改保存退货单
     */
    @RequiresPermissions("bill:aftersales:edit")
    @Log(title = "退货单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(BillAftersales billAftersales) {
        return toAjax(billAftersalesService.updateBillAftersales(billAftersales));
    }

    /**
     * 删除退货单
     */
    @RequiresPermissions("bill:aftersales:remove")
    @Log(title = "退货单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(billAftersalesService.deleteBillAftersalesByIds(ids));
    }


    /////////////////////////////////////////////////////////////////////////////////
    @Resource
    private IOmsOrderService orderService;
    @Resource
    private IBillAftersalesItemsService billAftersalesItemsService;
    @Resource
    private IBillRefundService billRefundService;
    @Resource
    private IBillReshipService billReshipService;
    @Resource
    private IBillExchangeService billExchangeService;
    @Resource
    private BillAftersalesOperateHistoryMapper billAftersalesOperateHistoryMapper;

    /**
     * 退换货列表
     *
     * @param entity
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/aftersalesList")
    public AjaxResult aftersalesList(BillAftersales entity,
                                     @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            IPage<BillAftersales> page = billAftersalesService.page(new Page<>(pageNum, pageSize), new QueryWrapper<>(entity));
            List<BillAftersales> recordList = new ArrayList<>();
            for (BillAftersales billAftersales : page.getRecords()) {
                // 查询订单信息
                OmsOrder omsOrder = orderService.getById(billAftersales.getAftersalesId());
                billAftersales.setOrderSn(omsOrder.getOrderSn());
                recordList.add(billAftersales);
            }
            page.setRecords(recordList);
            return AjaxResult.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 退货单详情
     *
     * @param id
     * @return
     */
    @GetMapping(value = "aftersalesDetail")
    public Object getOmsOrderById(Long id) {
        try {
            if (id == null) {
                return AjaxResult.error("id 不能为空！");
            }
            // 查询售后单
            BillAftersales billAftersales = billAftersalesService.getById(id);
            // 查询售后商品
            BillAftersalesItems billAftersalesItem = billAftersalesItemsService.getOne(new QueryWrapper<BillAftersalesItems>().eq("aftersales_id", billAftersales.getAftersalesId()));
            billAftersales.setBillAftersalesItems(billAftersalesItem);
            billAftersales.setOmsOrder(orderService.getById(billAftersales.getOrderId()));
            if (billAftersales.getType().equals(2)) {// 退货退款
                BillReship billReship = billReshipService.getOne(new QueryWrapper<BillReship>().eq("aftersales_id", billAftersales.getAftersalesId()));
                BillRefund billRefund = billRefundService.getOne(new QueryWrapper<BillRefund>().eq("aftersales_id", billAftersales.getAftersalesId()));
                billAftersales.setBillRefund(billRefund);
                billAftersales.setBillReship(billReship);
            } else if (billAftersales.getType().equals(3)) { // 换货
                BillExchange billExchange = billExchangeService.getOne(new QueryWrapper<BillExchange>().eq("aftersales_id", billAftersales.getAftersalesId()));
                billAftersales.setBillExchange(billExchange);
            }
            return AjaxResult.success(billAftersales);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 审核
     *
     * @return
     */
    @PostMapping(value = "audit")
    @ResponseBody
    public AjaxResult audit(Long aftersalesId, Integer aftersalesType, Integer auditType, String remark) {
        try {
            if (aftersalesId == null) {
                return AjaxResult.error("aftersalesId不能为空");
            }
            if (aftersalesType == null) {
                return AjaxResult.error("售后类型不能为空");
            }
            if (auditType == null) {
                return AjaxResult.error("审核类型不能为空");
            }
            if (remark == null) {
                return AjaxResult.error("备注不能为空");
            }
            billAftersalesService.doAudit(aftersalesId,aftersalesType,auditType,remark);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 退款
     */
    @PostMapping(value = "/refundAccmount")
    @ResponseBody
    public Object refundAccmount(Long aftersalesId) {
        try {
            if (aftersalesId == null) {
                return AjaxResult.error("aftersalesId参数为空");
            }
            // 修改退款状态
            BillAftersales billAftersales = billAftersalesService.getById(aftersalesId);
            billAftersales.setRefundStatus(2);  // 2=已退款
            //billAftersales.setAftersalesStatus(2);  // 2=已退款
            billAftersales.setStatus(2);
            billAftersalesService.updateById(billAftersales);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * 填写单号
     */
    @PostMapping(value = "/handleDeliverGoods")
    @ResponseBody
    public Object handleDeliverGoods(Long aftersalesId, String sellerLogiCode, String sellerLogiNo) {
        try {
            if (aftersalesId == null) {
                return AjaxResult.error("aftersalesId参数为空");
            }
            if (sellerLogiCode == null) {
                return AjaxResult.error("sellerLogiCode参数为空");
            }
            if (sellerLogiNo == null) {
                return AjaxResult.error("sellerLogiNo参数为空");
            }
            billAftersalesService.handleDeliverGoods(aftersalesId, sellerLogiCode, sellerLogiNo);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * 退货单详情
     */
    @GetMapping("/detail")
    public String detail(Long id, ModelMap mmap) {
        // 查询售后单
        BillAftersales billAftersales = billAftersalesService.getById(id);
        // 查询售后商品
        BillAftersalesItems billAftersalesItem = billAftersalesItemsService.getOne(new QueryWrapper<BillAftersalesItems>().eq("aftersales_id", billAftersales.getAftersalesId()));
        billAftersales.setBillAftersalesItems(billAftersalesItem);
        billAftersales.setOmsOrder(orderService.getById(billAftersales.getOrderId()));
        if (billAftersales.getType().equals(2)) {// 退货退款
            BillReship billReship = billReshipService.getOne(new QueryWrapper<BillReship>().eq("aftersales_id", billAftersales.getAftersalesId()));
            BillRefund billRefund = billRefundService.getOne(new QueryWrapper<BillRefund>().eq("aftersales_id", billAftersales.getAftersalesId()));
            billAftersales.setBillRefund(billRefund);
            billAftersales.setBillReship(billReship);
        } else if (billAftersales.getType().equals(3)) { // 换货
            BillExchange billExchange = billExchangeService.getOne(new QueryWrapper<BillExchange>().eq("aftersales_id", billAftersales.getAftersalesId()));
            billAftersales.setBillExchange(billExchange);
        }
        mmap.put("billAftersales", billAftersales);
        return prefix + "/detail";
    }

}
